import React, { useLayoutEffect, useRef } from "react";
import { Root } from "@amcharts/amcharts5";
import { PieChart, PieSeries } from "@amcharts/amcharts5/percent";
import AnimatedTheme from "@amcharts/amcharts5/themes/Animated";

export interface PieProps {
  data: {
    value: number | string;
    category: string;
  }[];
}

export const Pie: React.FC<PieProps> = ({ data = [] }) => {
  const chartRef = useRef<PieChart>();
  useLayoutEffect(() => {
    if (data.length === 0) return;

    // Create root element
    const root = Root.new("pie");

    // Set themes
    root.setThemes([AnimatedTheme.new(root)]);

    // Create chart
    const chart = root.container.children.push(
      PieChart.new(root, {
        layout: root.verticalLayout,
      })
    );

    // Create series
    const series = chart.series.push(
      PieSeries.new(root, {
        valueField: "value",
        categoryField: "category",
      })
    );

    // Set data
    series.data.setAll(data);
    chartRef.current = chart;

    return () => root.dispose();
  }, [data]);

  return (
    <div
      style={{
        height: 300,
      }}
      id="pie"
    />
  );
};
export default Pie;
